package cn.edu.pku.ss.music.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Log;
import cn.edu.pku.ss.music.entities.Music;

public class FindMusicTask extends AsyncTask<Void, Void, List<Music>> {
	private static final String TAG = "debug";
	private Context context;
	private List<Music> musics;

	public FindMusicTask(Context context) {
		this.context = context;
		this.musics = new ArrayList<Music>();
	}

	public void find() {
Log.d(TAG, "in find method");
		ContentResolver resolve = context.getContentResolver();
		Cursor cursor = resolve.query(
				MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
				MediaStore.Audio.Media.DEFAULT_SORT_ORDER);

		InputStream in = null;
		Bitmap bitmap = null;
Log.d(TAG, "size="+cursor.getCount());
		while (cursor.moveToNext()) {
Log.d(TAG, "in while");
			String title = cursor.getString(cursor
					.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
			String artist = cursor.getString(cursor
					.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
			String album = cursor.getString(cursor
					.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
			String album_id = cursor.getString(cursor
					.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID));

			Uri sArtworkUri = Uri
					.parse("content://media/external/audio/albumart");
			Uri uri = ContentUris.withAppendedId(sArtworkUri,
					Integer.valueOf(album_id));
			try {
				in = resolve.openInputStream(uri);
				bitmap = BitmapFactory.decodeStream(in);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}

			Music music = new Music();
Log.d(TAG, "title="+title);
Log.d(TAG, "singer="+artist);
			music.setTitle(title);
			music.setAlbum(album);
			music.setSinger(artist);
			music.setAlbum_art(bitmap);

			musics.add(music);
		}
Log.d(TAG, "end find method");
	}

	@Override
	protected List<Music> doInBackground(Void... params) {
		find();
		return musics;
	}
}
